/**
 * Copyright (c) 2020 qar All rights reserved.
 *
 * https://www.qar.io
 *
 * 版权所有，侵权必究！
 */

package io.qar.config;

import io.qar.filter.ValidateCodeFilter;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security配置
 *
 * @author Mark sunlightcs@gmail.com
 */
@AllArgsConstructor
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final UserDetailsService userDetailsService;
    private final ValidateCodeFilter validateCodeFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    /**
     * 密码模式需要
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception{
        return super.authenticationManager();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                // 设置CSP内容安全策略 禁用 X-Frame-Options 头部。X-Frame-Options 用于防止点击劫持（Clickjacking）攻击，但有时可能需要禁用它以允许页面嵌入到 iframe 中
            .headers().frameOptions().disable()
            .and()
            .addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
            .formLogin()
            .loginPage("/sso/login")
            .loginProcessingUrl("/sso/login")
            .and()
            .authorizeRequests() // 开始配置请求授权规则
            .antMatchers("/oauth/authorize").authenticated() // 指定 /oauth/authorize 路径需要用户认证后才能访问。
            .anyRequest().permitAll() // 所有其他请求都允许访问，无需认证
            .and().csrf().disable().formLogin().permitAll() // 禁用 CSRF 保护。CSRF 保护用于防止跨站请求伪造攻击
        ;

//        formLogin()：启用表单登录。
//        loginPage("/sso/login")：指定登录页面的 URL。
//        loginProcessingUrl("/sso/login")：指定处理登录请求的 URL。
    }


    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(HttpMethod.OPTIONS);
    }
}